package com.ky.server.main;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.ky.common.dto.Dto;
import com.ky.common.util.KeyConstants;
import com.ky.server.service.DownloadService;
import com.ky.server.service.FileListService;
import com.ky.server.service.LoginService;
import com.ky.server.service.RegisterService;
import com.ky.server.service.Service;
import com.ky.server.util.ConfigConstants;

public class ServerTaskRunnable implements Runnable{

	private Socket clientSocket;

	public ServerTaskRunnable(Socket clientSocket) {
		this.clientSocket = clientSocket;
	}

	@Override
	public void run() {
		ObjectInputStream ois=null;
		ObjectOutputStream oos=null;
		
		try {
			ois=new ObjectInputStream(clientSocket.getInputStream());
			oos=new ObjectOutputStream(clientSocket.getOutputStream());
			//服务器读取客户端发来的请求
			Dto<?> requestDto = (Dto<?>) ois.readObject();
			String key=requestDto.getKey();
			Service service=null;
			switch (key) {
			case KeyConstants.REGISTER:
				System.out.println("客户端"+clientSocket.getInetAddress().getHostAddress()+"："+clientSocket.getPort()+"发来请求--->"+KeyConstants.REGISTER);
				service=new RegisterService();
				break;
			case KeyConstants.LOGIN:
				System.out.println("客户端"+clientSocket.getInetAddress().getHostAddress()+"："+clientSocket.getPort()+"发来请求--->"+KeyConstants.LOGIN);
				service=new LoginService();
				break;
			case KeyConstants.FILELIST:
				System.out.println("客户端"+clientSocket.getInetAddress().getHostAddress()+"："+clientSocket.getPort()+"发来请求--->"+KeyConstants.FILELIST);
				service=new FileListService();
				break;
			case KeyConstants.DOWNLOAD:
				System.out.println("客户端"+clientSocket.getInetAddress().getHostAddress()+"："+clientSocket.getPort()+"发来请求--->"+KeyConstants.DOWNLOAD);
				service=new DownloadService();
				break;
			}
			//在服务器端进行业务处理，处理后返回dto对象
			Dto responseDto = service.service(requestDto.getData());
			oos.writeObject(responseDto);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(oos!=null) {
					oos.close();
				}
				if(ois!=null) {
					ois.close();
				}
				if(clientSocket!=null) {
					clientSocket.close();
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	
}
